package raptor;

import javax.swing.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class UDPServer {
    JFrame frame;
    JPanel panel;
    JButton button1,button2;
    JTextArea area;
    JScrollPane pane;
    Thread thread;
    DatagramSocket socket;

    public static void main(String[] args) {
        UDPServer u = new UDPServer();  
    }

    public UDPServer() {
        frame = new JFrame("Text Server");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setUndecorated(true);
        frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
        panel = new JPanel();
        panel.setLayout(null);
        area = new JTextArea();
        area.setEditable(false);
        button1 = new JButton("Start");
        button1.setBounds(210, 10, 75, 40);

        button1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ae) {
                new StartThread();
            }
        });

        panel.add(button1);
        button2 = new JButton("Stop");
        button2.setBounds(300, 10, 75, 40);

        button2.addActionListener(new ActionListener(){
            public void actionPerformed (ActionEvent ae) {
                thread.interrupted();
                socket.close();
                area.append("Server is stopped\n");
                button1.setEnabled(true);
                button2.setEnabled(false);
            }
        });

        button2.setEnabled(false);
        panel.add(button2);
        pane = new JScrollPane(area);
        pane.setBounds(10, 60, 365, 250);
        panel.add(pane);
        frame.add(panel);
        frame.setSize(400, 400);
        frame.setVisible(true);
    }

    public class StartThread extends SendRecieve implements Runnable  {
        public StartThread() {
            thread = new Thread(this);
            thread.start();
            button1.setEnabled(false);
            button2.setEnabled(true);
        }

        public void run() {
            listen(true);
        }

        public void output(byte[] buf, InetAddress client) {
            area.append("Received: " + new String(buf).trim() +" [" + client + "]:");
            area.append("\n");
            send(buf, client, PORT);
        }
    }
}
